package com.blogsystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.blogsystem.entity.Article;
import com.blogsystem.mapper.ArticleMapper;
import com.blogsystem.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.List;

@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;

    public List<Article> getPendingArticlesByUsername(String username) {
        if (username != null) {
            return articleMapper.selectList(new QueryWrapper<Article>()
                    .eq("user_id", username)
                    .eq("status", "pending")
                    .orderByDesc("create_time"));
        }

        return null;
    }

    public Page<Article> getArticlesByPage(int pageNum, int pageSize, Integer categoryId) {
        int offset = (pageNum - 1) * pageSize;
        // 根据分页和分类ID查询文章列表，用于展示已发布文章的分页数据
        List<Article> articles = articleMapper.selectArticlesByPage(categoryId, offset, pageSize);
        System.out.println("articles = " + articles);

        // 手动构建 Page 对象
        long total = getTotalCount(categoryId); // 你可以补充总数查询方法
        Page<Article> page = new Page<>(pageNum, pageSize);
        page.setRecords(articles);
        page.setTotal(total);
        return page;
    }

    // 获取总数（可选）
    private long getTotalCount(Integer categoryId) {
        // 可使用 count 查询或缓存
        return articleMapper.selectCount(null); // 示例简化处理
    }

    public List<Article> getAllArticlesByUserId(Integer userId) {
        if (userId != null) {
            return articleMapper.selectList(new QueryWrapper<Article>()
                    .eq("user_id", userId)
                    .orderByDesc("create_time"));
        }
        return null;
    }

    public List<Article> getDraftArticlesByUsername(String username) {

return  articleMapper.selectList(new QueryWrapper<Article>()
                .eq("user_id", username)
                .eq("status", "draft")
                .orderByDesc("create_time")); }

}
